package com.sl.leetcode;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by lisulong on 2019/5/27.
 */
public class Solution14 {

    public String longestCommonPrefix1(String[] strs) {
        String result = "";
        int resultIndex = 0;
        char strIndex;
        int arrCount = strs.length;
        while (true) {
            strIndex = '\0';
            int i;
            for (i = 0; i < arrCount; i++) {
                if (strIndex == '\0') strIndex = strs[i].charAt(resultIndex);
                else {
                    if (strIndex != strs[i].charAt(resultIndex))
                        break;
                }
            }
            if (i == arrCount) {
                result += strIndex;
                resultIndex++;
            } else {
                break;
            }
        }
        return result;
    }

    //    官方1--水平扫描法
    public String longestCommonPrefix2(String[] strs) {
        if (strs.length == 0) return "";
        String prefix = strs[0];
        for (int i = 1; i < strs.length; i++)
            while (strs[i].indexOf(prefix) != 0) {
                prefix = prefix.substring(0, prefix.length() - 1);
                if (prefix.isEmpty()) return "";
            }
        return prefix;
    }

    //    官方2--水平扫描法
    //    想象数组的末尾有一个非常短的字符串，使用上述方法依旧会进行 S​S​ 次比较。优化这类情况的一种方法就是水平扫描。
    // 我们从前往后枚举字符串的每一列，先比较每个字符串相同列上的字符（即不同字符串相同下标的字符）然后再进行对下一列的比较。
    public String longestCommonPrefix3(String[] strs) {
        if (strs == null || strs.length == 0) return "";
        for (int i = 0; i < strs[0].length() ; i++){
            char c = strs[0].charAt(i);
            for (int j = 1; j < strs.length; j ++) {
                if (i == strs[j].length() || strs[j].charAt(i) != c)
                    return strs[0].substring(0, i);
            }
        }
        return strs[0];
    }


    public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class<Solution14> clz = Solution14.class;
        Object obj = clz.newInstance();
        Method longestCommonPrefix;
        for (int i = 1; i <= 3; i++) {
            long startTime = System.nanoTime();
            longestCommonPrefix = clz.getMethod("longestCommonPrefix" + i, String[].class);
            System.out.println(longestCommonPrefix.invoke(obj, new Object[]{new String[]{"flflflflflflflflflflflower", "flflflflflflflflflflflflow", "flflflflflflflflflflflflight"}}));//数组做为参数的，需要使用new Object[]{}包一层
            System.out.println("====耗时：" + (System.nanoTime() - startTime));
        }
    }
}
